package com.twetec.cms.adapter.pc.backend.util.beetl.html;


import cn.hutool.core.io.FileUtil;
import com.twetec.cms.adapter.pc.backend.util.beetl.thread.HtmlThread;

import com.twetec.cms.service.website.SiteService;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.StringWriter;
import java.util.Map;

@Component
public class BeetlStaticHtml {

	@Autowired
	private GroupTemplate groupTemplate;

	@Autowired
	private SiteService siteService;

	/**
	 * 创建静态文件
	 * @param templateFilePath 模板文件路径
	 * @param staticHtmlFilePath 静态文件存放地址
	 * @param attr 模板属性
	 */
	public void create(String templateFilePath, String staticHtmlFilePath, Map<String, Object> attr) {

		// 模板内容替换
		Template template = groupTemplate.getTemplate(templateFilePath);

		StringWriter writer = new StringWriter();
		template.binding(attr);
		template.renderTo(writer);

		// 写入html文件
		HtmlObject obj = new HtmlObject();
		obj.setContent(writer.toString());
		new File(staticHtmlFilePath).delete();
		obj.setFileUrl(staticHtmlFilePath);
		HtmlThread.addHtml(obj);
	}

	/**
	 * 生成页面字符串
	 * @param templateFilePath
	 * @param attr
	 * @return
	 */
	public String getTemplateRenderContent(String templateFilePath, Map<String, Object> attr) {
		// 模板内容替换
		Template template = groupTemplate.getTemplate(templateFilePath);

		StringWriter writer = new StringWriter();
		template.binding(attr);
		template.renderTo(writer);

		// 写入html文件
		return writer.toString();
	}
}
